package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Override
    public void insert(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBookMapper.insert(addressBook);
    }

    @Override
    public List<AddressBook> list() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        return addressBookMapper.select(addressBook);
    }

    @Override
    public AddressBook selectById(Long id) {
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        return addressBookMapper.select(addressBook).get(0);
    }

    @Override
    public AddressBook selectDefault() {
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressBook.setUserId(BaseContext.getCurrentId());      // 将当前用户的，不能设置所有
        List<AddressBook> addressBookList = addressBookMapper.select(addressBook);
        if(addressBookList == null || addressBookList.isEmpty()) {
            return null;
        }
        return addressBookList.get(0);
    }

    @Override
    public void updateById(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public void setDefault(Long id) {
        // 将所有默认地址改为false
        AddressBook tmp = new AddressBook();
        tmp.setIsDefault(StatusConstant.DISABLE);
        tmp.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(tmp);


        tmp.setId(id);
        tmp.setIsDefault(StatusConstant.ENABLE);
        addressBookMapper.update(tmp);
    }
}
